package models

import (
	"gitee.com/lzqysoft/framework/services/base/lib/jwt"
	"gitee.com/lzqysoft/framework/common/log"
)



func GetJwt(token string) (*User, *Organ, string, error) {
	easyToken, tokenString, err := jwt.Parse(token)
	if err != nil {
		return nil, nil, "", err
	}
	user,err := GetUserById(easyToken.Userid)
	if err != nil {
		return  nil, nil, "", err
	}
	organ, err := GetOrganById(easyToken.Orgid)
	if err != nil {
		return  nil, nil, "", err
	}
	return user,organ,tokenString, nil
}


	func GetMenusByUserIdAndGroupId(userId, groupId string) []map[string]interface{} {
	groups := GetGroupsByUserId(userId)
	groupAuthoritys := GetGroupAuthorityByGroupId(groupId)
	userAuthoritys := GetUserAuthorityByUserId(userId)
	authid := make([]string,0)
	for _, v := range groupAuthoritys {
		authid = append(authid, v.AuthorityId)
	}
	for _, v := range userAuthoritys {
		authid = append(authid, v.AuthorityId)
	}
	if len(authid) <= 0 {
		log.Error("该用户无任何权限")
		return nil
	}
	modules := GetModulesByIdSlice(authid)
	if len(modules) <= 0 {
		log.Error("获取权限异常")
		return nil
	}
	return generateMenus(modules)
}

func generateMenus(ms []Module) []map[string]interface{} {
	tree := make([]map[string]interface{},0)
	for _, v := range ms {
		// 判断root模块
		if v.Category == "00" && v.Pid == "root" {
			item := v.Convert2Map()
			generateMap(&v, item, ms)
			tree = append(tree, item)
		}
	}
	return tree
}

func generateMap(parent *Module, item map[string]interface{}, ms []Module) {
	for _, v := range ms {
		if  v.Pid == parent.Id {
			child := v.Convert2Map()
			item["Child"] = child
			generateMap(&v, child, ms)
		}
	}
}